const oss = require('ali-oss')
import {
	getOssSts
} from '@/api/common'
import {
	getImageWidthAndHeight
} from '@/utils'


let bucket = "cfdz-sz-test"
if (process.env.NODE_ENV == 'production-pro') {
	bucket = "cfdz-sz"
}


/**
 * @param {object} option - folder 要上传的目名名称
 * - folder 要上传的目名名称
 */
export default class OSSClient {
	private option: any
	private accessKeyId: string | undefined
	private accessKeySecret: string | undefined
	private stsToken: string | undefined
	private region: string | undefined
	private bucket: string | undefined
	private client: any
	constructor(option?:any) {
		var defaultOption = {
			folder: 'public'
		}
		this.option = Object.assign(defaultOption, option)

	}
	private init() {
		return new Promise<void>((resolve, reject) => {
			getOssSts().then(res => {
				this.accessKeyId = res.data.Credentials.AccessKeyId
				this.accessKeySecret = res.data.Credentials.AccessKeySecret
				this.stsToken = res.data.Credentials.SecurityToken
				this.region = 'oss-cn-shenzhen'
				this.bucket = bucket
				this.client = oss({
					accessKeyId: this.accessKeyId,
					accessKeySecret: this.accessKeySecret,
					stsToken: this.stsToken,
					region: this.region,
					bucket: this.bucket,
				})
				resolve()
			}).catch(err => {
				reject("oss获取服务器签名失败")
			})
		})

	}
	uploadFile(localFile:File) {
		return new Promise((resolve, reject) => {
			this.init().then(async res => {
				//	multipartUpload  分片上传   针对传大图
				//	put  普通上传   不会有太大的图的情况下用
				let extraStr = ""
				if (localFile.type.indexOf('image') != -1) {
					let imgInfo = await getImageWidthAndHeight(localFile)
					extraStr = `${imgInfo.width}x${imgInfo.height}`
				}

				this.client.put(this.createOssPath(localFile, extraStr), localFile).then(res => {
					resolve(`https://${this.bucket}.${this.region}.aliyuncs.com/` + res.name)
				}).catch(err => {
					reject(err)
				})
			})

		})
	}
	private createOssPath(file, extraStr = '') {
		let folder = this.option.folder

		let year = this.dateFormat(new Date(), 'yyyy')
		let month = this.dateFormat(new Date(), 'MM')
		let day = this.dateFormat(new Date(), 'dd')
		if (extraStr) {
			extraStr += '_'
		}
		let name = `${year}/${month}/${day}/${extraStr}${this.randomString(16)}`

		let type = file.name.split('.')
		type = type[type.length - 1]

		if (folder && folder.charAt(folder.length - 1) !== '/') {
			folder = folder + '/'
		}
		let fileName = 'store/' + folder + name + '.' + type

		return fileName
	}
	private dateFormat(d, fmt = 'yyyy-MM-dd hh:mm:ss') {
		if (typeof d == 'string') {
			if (d.length == 10) d = d + '000'
			if (!isNaN(d)) d = Number(d)
		}
		if (typeof d == 'number') {
			if (d.toString().length == 10) d = d * 1000
		}
		if (!(d instanceof Date)) {
			d = new Date(d)
		}
		var o = {
			"M+": d.getMonth() + 1, //月份
			"d+": d.getDate(), //日
			"h+": d.getHours(), //小时
			"m+": d.getMinutes(), //分
			"s+": d.getSeconds(), //秒
			"q+": Math.floor((d.getMonth() + 3) / 3), //季度
			"S": d.getMilliseconds() //毫秒
		};
		if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
	}
	private randomString(len) {
		len = len || 32;
		var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		var maxPos = $chars.length;
		var pwd = '';
		for (let i = 0; i < len; i++) {
			pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return pwd;
	}

}
